<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <title>Admin - Order Management</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- Bootstrap CSS + FontAwesome -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <style>
    body {
      font-family: Arial, sans-serif;
      background-color: #f4f4f4;
      margin: 0; padding: 0;
    }
    .admin-nav {
      background-color: #fff;
      padding: 10px;
      box-shadow: 0 1px 4px rgba(0,0,0,0.1);
    }
    .container {
      margin-top: 20px;
    }
    .filter-btn {
      margin: 0 4px 8px;
    }
    .order-card {
      background: #fff;
      border-radius: 10px;
      box-shadow: 0 2px 5px rgba(0,0,0,0.1);
      padding: 12px;
      font-size: 0.9rem;
      line-height: 1.4;
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
    }
    .order-card h5 {
      font-size: 1rem;
      margin-bottom: 8px;
    }
    .order-card p {
      margin: 2px 0;
    }
    .order-card .btn-sm {
      font-size: 0.8rem;
      padding: 2px 6px;
    }
  </style>
  <script>
    if (localStorage.getItem('isAdminLoggedIn') !== 'true') {
      window.location.href = 'login.html';
    }
  </script>
</head>
<body>

  <!-- 导航 -->
  <nav class="admin-nav text-center">
    <a href="vehicle-admin.html" class="btn btn-primary me-2 mb-2">车辆管理</a>
    <a href="order-admin.html"   class="btn btn-secondary mb-2">订单管理</a>
  </nav>

  <div class="container">
    <h2 class="text-center mb-4">Admin – Order Management</h2>

    <!-- 筛选按钮 -->
    <div class="text-center mb-3">
      <button class="btn btn-outline-primary filter-btn" onclick="filterOrders('all', this)">
        <span>全部</span><br><small class="text-muted">All</small>
      </button>
      <button class="btn btn-outline-primary filter-btn" onclick="filterOrders('pending', this)">
        <span>待处理</span><br><small class="text-muted">Pending</small>
      </button>
      <button class="btn btn-outline-success filter-btn" onclick="filterOrders('confirmed', this)">
        <span>已确认</span><br><small class="text-muted">Confirmed</small>
      </button>
      <button class="btn btn-outline-danger filter-btn" onclick="filterOrders('canceled', this)">
        <span>已取消</span><br><small class="text-muted">Canceled</small>
      </button>
    </div>

    <!-- 订单列表响应式栅格 -->
    <div class="row row-cols-1 row-cols-sm-2 row-cols-xl-3 g-3" id="orderList">
      <!-- JS 动态插入 .col > .order-card -->
    </div>
  </div>
  </footer>

  <!-- Bootstrap JS -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  <!-- Firestore 脚本（保持和你现有逻辑一致） -->
  <script type="module">
    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.22.2/firebase-app.js";
    import {
      getFirestore, collection, onSnapshot,
      updateDoc, deleteDoc, doc
      
    } from "https://www.gstatic.com/firebasejs/9.22.2/firebase-firestore.js";

    const firebaseConfig = {
      apiKey: "YOUR_API_KEY",
      authDomain: "rental-7fe8c.firebaseapp.com",
      projectId: "rental-7fe8c",
      storageBucket: "rental-7fe8c.appspot.com",
      messagingSenderId: "263132536954",
      appId: "1:263132536954:web:55d988d88b1a078b4b9bc3"
    };

    const app = initializeApp(firebaseConfig);
    const db = getFirestore(app);

    let globalOrders = [];

    onSnapshot(collection(db, "orders"), snap => {
      globalOrders = [];
      snap.forEach(d => globalOrders.push({ id: d.id, ...d.data() }));
      renderOrders(globalOrders);
    });

    function renderOrders(list) {
      const container = document.getElementById("orderList");
      container.innerHTML = "";

      list.forEach((order, idx) => {
        const status = order.status || "pending";

        // 按钮
        const btnConfirm = status === "pending"
          ? `<button class="btn btn-sm btn-success me-1" onclick="updateStatus('${order.id}','confirmed')">确认 / Confirm</button>`
          : `<button class="btn btn-sm btn-success me-1" disabled>已确认 / Confirmed</button>`;
        const btnCancel = status !== "canceled"
          ? `<button class="btn btn-sm btn-danger" onclick="updateStatus('${order.id}','canceled')">取消 / Cancel</button>`
          : `<button class="btn btn-sm btn-warning" onclick="updateStatus('${order.id}','pending')">恢复 / Restore</button>`;

        // 时间
        let timeStr = "——";
        if (order.createdAt && order.createdAt.toDate) {
          timeStr = order.createdAt.toDate().toLocaleString();
        }

        // 中文块
        const zh = `
          <div class="flex-half">
            <h5>订单 ${idx+1}</h5>
            <p><strong>时间：</strong>${timeStr}</p>
            <p><strong>车辆：</strong>${order.carName||"--"}</p>
            <p><strong>客户：</strong>${order.name||"--"} / ${order.phone||"--"}</p>
            <p><strong>取／还：</strong>${order.startDate||"--"} → ${order.endDate||"--"}</p>
            <p><strong>天数：</strong>${order.days||0} 天　<strong>租金：</strong>${order.rentalPrice||0} ฿</p>
            <p><strong>押金：</strong>${order.deposit!=null?order.deposit+" ฿":"未付"}</p>
            <p><strong>状态：</strong>${status}</p>
          </div>`;

        // English block
        const en = `
          <div class="flex-half">
            <h5>Order ${idx+1}</h5>
            <p><strong>Time:</strong> ${timeStr}</p>
            <p><strong>Car:</strong> ${order.carName||"Unknown"}</p>
            <p><strong>Customer:</strong> ${order.name||"--"} / ${order.phone||"--"}</p>
            <p><strong>Pick/Return:</strong> ${order.startDate||"--"} → ${order.endDate||"--"}</p>
            <p><strong>Days:</strong> ${order.days||0} days　<strong>Rent:</strong> ${order.rentalPrice||0} ฿</p>
            <p><strong>Deposit:</strong> ${order.deposit!=null?order.deposit+" ฿":"Unpaid"}</p>
            <p><strong>Status:</strong> ${status}</p>
          </div>`;

        const card = document.createElement("div");
        card.className = "order-card col";
        card.innerHTML = `
          <div class="d-flex flex-wrap">
            ${zh}
            ${en}
          </div>
          <div class="mt-3 text-end">
            ${btnConfirm}${btnCancel}
          </div>
        `;
        container.appendChild(card);
      });
    }
    
    window.filterOrders = (st, btn) => {
      document.querySelectorAll('.filter-btn').forEach(b=>b.classList.remove('active'));
      btn.classList.add('active');
      renderOrders(st==='all' ? globalOrders : globalOrders.filter(o => (o.status||'pending')===st));
    };

      window.updateStatus = async (id, st) => {
        const ref = doc(db, "orders", id);
        if (st === 'canceled') {
        // 直接删除文档
        if (confirm("确定要删除该订单吗？这一操作不可恢复！")) {
          await deleteDoc(ref);
        }
        } else {
          // 其它状态走更新
          await updateDoc(ref, { status: st });
        }
      };
  </script>
</body>
</html>